package com.spring.transaction.dao;


import com.spring.transaction.exception.BookStockException;
import com.spring.transaction.exception.UserAccountException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("bookShopDao")
public class BookShopDaoImpl implements BookShopDao {

    @Autowired
    private JdbcTemplate JdbcTemplate;

    @Override
    public int findBookPriceBySerialNum(Integer bookNum) {
        // create table book (id int primary key,price int,serial_num int);
        String sql = "SELECT price FROM book WHERE serial_num = ?";
        return (int) JdbcTemplate.queryForObject(sql,new Object[]{bookNum}, Integer.class);
    }

    @Override
    public void updateBookStock(Integer bookNum) throws BookStockException {
        //create table book_stock (id int primary key,stock int,serial_num int);
        //检查书的库存是否足够，若不够，则抛出异常
        String sql = "SELECT stock FROM book_stock WHERE serial_num = ?";
        Integer stock= (Integer)JdbcTemplate.queryForObject(sql,new Object[]{bookNum}, Integer.class);
        if (stock == 0) {
            throw new BookStockException("库存不足！");
        }
        sql = "UPDATE book_stock SET stock = stock - 1 WHERE serial_num = ?";
        JdbcTemplate.update(sql, new Object[]{bookNum});
    }

    @Override
    public void updateUserAccount(String userName, int price) throws UserAccountException {
        // create table account (id int primary key,username varchar(10),balance int);
        //检查余额是否不足，若不足，则抛出异常
        String sql = "SELECT balance FROM account WHERE username = ?";
        int balance = (int)JdbcTemplate.queryForObject(sql, new Object[]{userName},Integer.class);
        if (balance < price) {
            throw new UserAccountException("余额不足！");
        }
        sql = "UPDATE account SET balance = balance - ? WHERE username = ?";
        JdbcTemplate.update(sql, new Object[]{price, userName});
    }

}
